package com.easyattendance.servlets;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.easyattendance.model.Class;
import com.easyattendance.model.Material;
import com.easyattendance.model.MaterialClass;
import com.easyattendance.model.MaterialSection;
import com.easyattendance.model.Teacher;
import com.easyattendance.nls.UseProperties;
import com.easyattendance.services.AddMaterialService;
import com.easyattendance.services.AddSubjectService;
import com.easyattendance.services.AddTeacherService;

@WebServlet("/AddMaterialServlet")
@MultipartConfig
public class AddMaterialServlet extends HttpServlet  {
	private static final long serialVersionUID = 1L;
	private boolean error=false;
	public String path=null;
	public String message=null;
    
	protected void processRequest(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
	{
		response.setContentType("text/html;charset=UTF-8");
		
		boolean dispatcherFlag = false;
		boolean result=false;
		
		AddSubjectService subjectService=new AddSubjectService();
		AddMaterialService materialService=new AddMaterialService();
		AddTeacherService teacherService=new AddTeacherService();

		 String actionType = request.getParameter("action_type");
		 String userType=request.getParameter("user_type");
		 
		 String ID=null;
		 
		 if(actionType.equals("create") && userType.equals("teacher"))
		 {
			 	String material_no=request.getParameter("material_id");
			 	String material_name=request.getParameter("material_name");
			 	String class_id=request.getParameter("select_class");
				String subject_name=request.getParameter("subject_name");
				String category=request.getParameter("category");
				String file_location=path+"\\"+request.getParameter("file_name");
				String teacher_id=request.getParameter("teacher_id");
				
				
				if(class_id.isEmpty() || subject_name.isEmpty() || category.isEmpty() || file_location.isEmpty())
				{
		        	dispatcherFlag = true;					
				}				
				
				if(!dispatcherFlag)
				{
					String subject_id=subjectService.getSubjectIdBySubjectName(subject_name);
					String uploaded_by=teacherService.getTeacherById(teacher_id).getTeacher_name()+" "+teacherService.getTeacherById(teacher_id).getTeacher_lname();
					
					Properties labels = UseProperties.loadProperties("Attendance.properties");
	            	labels = UseProperties.incrementMaterialIdCounterValue(labels);
	            	ID = UseProperties.getMaterialIdPrefix(labels)+material_no;
	            	
					Teacher teacher=teacherService.getTeacherById(teacher_id);
					Material material=new Material(ID,material_name,category,uploaded_by,file_location);				
					
					boolean res=materialService.ifAlreadyExists(material);
					
					if(!res)
					{
						 MaterialClass materialClass=new MaterialClass(ID,class_id,subject_id);
						 materialClass.setTeacher(teacher);
						 materialClass.setMaterial(material);
						 result=materialService.addMaterialForClass(material,materialClass);
					}
					else
					{
						if(!error)
						{	
							request.setAttribute("materialExists", "Material is already uploaded.");
							RequestDispatcher rd = request.getRequestDispatcher("views/teacher/addMaterial.jsp");
				        	rd.forward(request, response); 
						}
					}				
				
					if(result)
					{
						if(!error)
						{	
							request.setAttribute("materialAdded", "Material uploaded Successfully.");
					        RequestDispatcher rd = request.getRequestDispatcher("views/teacher/addMaterial.jsp");
					        rd.forward(request, response);
					        //return;
						}  
						else
					    {
						        request.setAttribute("file_upload_error",message);
					        	RequestDispatcher rd = request.getRequestDispatcher("views/teacher/addMaterial.jsp");
					        	rd.forward(request, response);
					        	//return;
					    }
					}
					else
					{
						if(!error)
						{
							request.setAttribute("materialNotAdded", "Material could not be uploaded successfully.");
				        	RequestDispatcher rd = request.getRequestDispatcher("views/teacher/addMaterial.jsp");
				        	rd.forward(request, response);
				        	
							Properties label1 = UseProperties.loadProperties("Attendance.properties");
			            	label1 = UseProperties.decrementMaterialIdCounterValue(label1);
						}
						else
					    {
						        request.setAttribute("file_upload_error",message);
					        	RequestDispatcher rd = request.getRequestDispatcher("views/teacher/addMaterial.jsp");
					        	rd.forward(request, response);
					        	//return;
					    }
					}
				}
				else
				{
						request.setAttribute("null_values", "All * fields are required.");
						RequestDispatcher rd = request.getRequestDispatcher("views/teacher/addMaterial.jsp");
			        	rd.forward(request, response); 
				}
		 
		 }
		 else if(actionType.equals("delete") && userType.equals("teacher")) {
				
			 String materials[] = request.getParameterValues("material_id");
				
				 String checkbox_list[]=new String[materials.length];
				 
				 for(int i=0;i<materials.length;i++)
				 {
						   checkbox_list[i]=request.getParameter("checkbox"+(i+1));
				 }
				 
				String classes[] = request.getParameterValues("class_id");
				String subjectNames[] = request.getParameterValues("subject_name");
				
				for(int i=0;i<materials.length;i++)
				{
					 if(checkbox_list[i]!=null)
					 {
						   String materialId=materials[i];
						   String classId=classes[i];
						   String subjectId=subjectService.getSubjectIdBySubjectName(subjectNames[i]);
						   
						   boolean res1 =materialService.deleteFromMaterialClass(materialId, classId, subjectId);
						   boolean res=materialService.deleteMaterial(materialId);

					 }
						 
				}
				response.sendRedirect("views/teacher/materialSettings.jsp");
		
			}
		 else if(userType.equals("section") && actionType.equals("create"))
		 {
			 
			 	String material_no=request.getParameter("material_id");
			 	String material_name=request.getParameter("material_name");
			 	String class_id=request.getParameter("class_id");
				String file_location=path+"\\"+request.getParameter("file_name");
				String category="circular";
				String subject_id=null;
				String section_id=request.getParameter("section_id");
				String uploaded_by = request.getParameter("section_name");
				
				Properties labels = UseProperties.loadProperties("Attendance.properties");
				labels = UseProperties.incrementMaterialIdCounterValue(labels);
				ID = UseProperties.getMaterialIdPrefix(labels)+material_no;
         		
				Material material=new Material(ID,material_name,category,uploaded_by,file_location);
				boolean res=materialService.ifAlreadyExists(material);
				
				if(file_location.isEmpty() || class_id.isEmpty() || material_name.isEmpty() || material_no.isEmpty())
				{
		        	dispatcherFlag = true;					
				}
				
				
				if(!dispatcherFlag)
				{
					if(!res)
					{
						 MaterialSection materialSection=new MaterialSection(ID,section_id);
						 if(!class_id.equals("For all classes"))
						 {	 Class classObj=new Class(class_id);
						 	 materialSection.setClassObj(classObj);
						 }
						 else
						 {
							 materialSection.setClassObj(null);
						 }
						 
						 materialSection.setMaterial(material);
						 result=materialService.addMaterialForSection(material,materialSection);
					}
					else
					{
						if(!error)
						{	
							request.setAttribute("materialExists", "Material is already uploaded");
							RequestDispatcher rd = request.getRequestDispatcher("views/section/addMaterial.jsp");
				        	rd.forward(request, response); 
						}
					}				
				
					if(result)
					{
						 if(!error)
						 {	
								request.setAttribute("materialAdded", "Material uploaded Successfully.");
						        RequestDispatcher rd = request.getRequestDispatcher("views/section/addMaterial.jsp");
						        rd.forward(request, response); 
								//response.sendRedirect("views/section/addMaterial.jsp");
						       
						 }  
						 else
						 {
							        request.setAttribute("file_upload_error",message);
						        	RequestDispatcher rd = request.getRequestDispatcher("views/section/addMaterial.jsp");
						        	rd.forward(request, response);
						        	
						 }
					}
				}
				else
				{
						request.setAttribute("null_values", "All * fields are required.");
						RequestDispatcher rd = request.getRequestDispatcher("views/section/addMaterial.jsp");
			        	rd.forward(request, response); 
				}
		 }
		 else if(actionType.equals("delete") && userType.equals("section")) {
			 String materials[] = request.getParameterValues("material_id");
				
			 String checkbox_list[]=new String[materials.length];
			 
			 for(int i=0;i<materials.length;i++)
			 {
					   checkbox_list[i]=request.getParameter("checkbox"+(i+1));
			 }
			 
			String sectionId = request.getParameter("section_id");
		
			 boolean res1 = false,res = false;
			for(int i=0;i<materials.length;i++)
			{
				 if(checkbox_list[i]!=null)
				 {
					   String materialId=materials[i];
					  
					   res1 =materialService.deleteFromMaterialSection(materialId,sectionId);
					   res=materialService.deleteMaterial(materialId);

				 }
					 
			}
			response.sendRedirect("views/section/materialSettings.jsp");
			
			  /*if(res && res1){
					request.setAttribute("materialDeleted", "Material deleted successfully.");
		        	RequestDispatcher rd = request.getRequestDispatcher("views/section/materialSettings.jsp");
		        	rd.forward(request, response);
				}
				else {
					request.setAttribute("materialNotDeleted", "Material Not deleted successfully.");
		        	RequestDispatcher rd = request.getRequestDispatcher("views/teacher/materialSettings.jsp");
		        	rd.forward(request, response);
				} */
			} 
		
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		processRequest(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		// Create path components to save the file
		final String new_folder="C:\\uploadedfiles";
    
	    String userType=request.getParameter("user_type");
	    
	    if(!userType.equals("section"))
	    {
	    	final String folder1_path = new_folder+"\\"+request.getParameter("select_class");
	    	
	    	final String folder1=request.getParameter("select_class");
	    	final String folder2 = new_folder+"\\"+folder1+"\\Material";
	    	final String folder3=folder2+"\\"+request.getParameter("subject_name");
	    
		    boolean success=(new File(new_folder)).mkdir();
	   	 	if(success)
	   		  System.out.print("Directory "+new_folder+" created successfully");
	
		    success=(new File(folder1_path)).mkdir();
	   	 	if(success)
	   		  System.out.print("Directory "+folder1_path+" created successfully");
	
	   	 	success=(new File(folder2)).mkdir();
		 	if(success)
			  System.out.print("Directory "+folder2+" created successfully");
		    
		 	success=(new File(folder3)).mkdir();
		 	if(success)
			  System.out.print("Directory "+folder3+" created successfully");
		 	
		 	   path=folder3;
	    }
	    else if(userType.equals("section"))
	    {
	    	final String folder1=new_folder+"\\"+"section";
	    	final String class_id=request.getParameter("class_id");
	    	final String section_name=request.getParameter("section_name");
	     
	    	final String folder2=folder1+"\\"+section_name;
	        String folder3 = null;
	    	
	    	 boolean success=(new File(new_folder)).mkdir();
		   	 	if(success)
		   	 		System.out.print("Directory "+new_folder+" created successfully");
		   	 
		   	 success=(new File(folder1)).mkdir();
		   	 	if(success)
		   	 		System.out.print("Directory "+folder1+" created successfully");
		   	 
		   	 success=(new File(folder2)).mkdir();
		   	 	if(success)
		   	 		System.out.print("Directory "+folder2+" created successfully");
		   	 	
		   	 if(!class_id.equals("null"))
		   	 {
		   		  folder3=folder2+"\\"+class_id;
		   		 
			   		success=(new File(folder3)).mkdir();
			   	 	if(success)
			   	 		System.out.print("Directory "+folder3+" created successfully");
		   		 
		   	 }
		   	 else if(class_id.equals("null"))
		   	 {
		   		 folder3=folder2+"\\"+"common";
		   		 
		   		 success=(new File(folder3)).mkdir();
		   	 	 if(success)
		   	 		System.out.print("Directory "+folder3+" created successfully");
	   		 
		   	 }
		   	 path=folder3;
	    	
	    }
	    
	    final Part filePart = request.getPart("fileName");
	    final String fileName = getFileName(filePart);

	    OutputStream out = null;
	    InputStream filecontent = null;
	    //final PrintWriter writer = response.getWriter();
	    

	    try {
	    	
	        out = new FileOutputStream(new File(path + File.separator
	                + fileName));
	        filecontent = filePart.getInputStream();

	        int read = 0;
	        final byte[] bytes = new byte[1024];

	        while ((read = filecontent.read(bytes)) != -1) {
	            out.write(bytes, 0, read);
	        }
	        System.out.println("New file " + fileName + " created at " + path);
	       /* LOGGER.log(Level.INFO, "File{0}being uploaded to {1}", 
	                new Object[]{fileName, path}); */
	    } catch (FileNotFoundException fne) {
	        message="You either did not specify a file to upload or are "
	                + "trying to upload a file to a protected or nonexistent "
	                + "location.";
	     
	        error=true;
	       
	       /* LOGGER.log(Level.SEVERE, "Problems during file upload. Error: {0}", 
	                new Object[]{fne.getMessage()}); */
	    } finally {
	        if (out != null) {
	            out.close();
	        }
	        if (filecontent != null) {
	            filecontent.close();
	        }
	       /* if (writer != null) {
	            writer.close();
	        } */
	    }
	    
	    	processRequest(request, response);			
	   
	}
	
	private String getFileName(final Part part) {
	    final String partHeader = part.getHeader("content-disposition");
	   // LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);
	    for (String content : part.getHeader("content-disposition").split(";")) {
	        if (content.trim().startsWith("filename")) {
	            return content.substring(
	                    content.indexOf('=') + 1).trim().replace("\"", "");
	        }
	    }
	    return null;
  }
}
